package chatBot.common;

import chatBot.exception.CustomException;
import chatBot.exception.IllegalOperationException;
import chatBot.exception.NoPermissionException;
import chatBot.exception.NoTokenCountException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

/**
 * 全局异常处理器，用于统一处理应用程序中的异常。
 * 该处理器适用于带有@RestController和@Controller注解的类。
 */
@ControllerAdvice(annotations = {RestController.class, Controller.class})
@Slf4j
@ResponseBody // 返回JSON格式的数据
public class GlobalExceptionHandler {

    /**
     * 自定义异常处理方法。
     * 当抛出CustomException时，该方法将捕获异常，记录错误日志，并返回错误响应。
     *
     * @param ex 捕获到的CustomException异常
     * @return 包含错误信息的Result对象
     */
    @ExceptionHandler(CustomException.class)
    public Result<Object> CustomExceptionHandler(CustomException ex) {
        log.error(ex.getMessage());
        return Result.fail(ex.getMessage());
    }

    @ExceptionHandler(IllegalOperationException.class)
    public Result<Object> IllegalOperationExceptionHandler(IllegalOperationException ex) {
        log.error(ex.getMessage());
        return Result.fail(ex.getMessage());
    }

    //NoPermissionException
    @ExceptionHandler(NoPermissionException.class)
    public Result<Object> NoPermissionExceptionHandler(NoPermissionException ex) {
        log.error(ex.getMessage());
        return Result.fail(ex.getMessage());
    }

    //NoTokenCountException
    @ExceptionHandler(NoTokenCountException.class)
    public Result<Object> NoTokenCountExceptionHandler(NoTokenCountException ex) {
        log.error(ex.getMessage());
        return Result.fail(ex.getMessage());
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResponseEntity<Map<String, String>> handleValidationExceptions(MethodArgumentNotValidException ex) {
        Map<String, String> errors = new HashMap<>();
        ex.getBindingResult().getFieldErrors().forEach(error ->
                errors.put(error.getField(), error.getDefaultMessage()));
        return new ResponseEntity<>(errors, HttpStatus.BAD_REQUEST);
    }


}
